package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;


public class GroupHelper extends HelperWithWebDriverBase {
	
	//private Set<GroupObject> groupCashe;
	private Groups groupCashe;
	
	private Groups groups;

	public GroupHelper(ApplicationManager manager) {
		super(manager);
	}
	
//	public Set<GroupObject> getGroups() {
//		if (groupCashe == null) {
//			buildGroupCashe();
//		}
//		return groupCashe;	
//	}
	
	public Groups getGroups() {
		if (groupCashe == null) {
			buildGroupCashe();
		}
		return groupCashe;	
	}
	
	private void buildGroupCashe() {
		//groupCashe = new HashSet<GroupObject>();
		HashSet<GroupObject> set = new HashSet<GroupObject>();
		manager.getNavigationHelper().goToGroupListPage();
		WebElement form = findElements(By.tagName("form")).get(1);
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			Pattern p = Pattern.compile(".*\\((.*)\\)");
			Matcher m = p.matcher(title);
			if (m.matches()) {
				title = m.group(1);
			} 
			GroupObject group = new GroupObject()
				.setName(title)
				.setId(checkbox.getAttribute("value"));
			//groupCashe.add(group);
			set.add(group);
		}
		groupCashe = new Groups(set);
	}
	
	public void createGroup(GroupObject groupObject) {
		manager.getNavigationHelper().goToGroupListPage();
		initGroupCreation();
		fillGroupForm(groupObject);
		submitGroupCreation();
		returnToGroupListPage();
		buildGroupCashe();
	}	
	
	private void returnToGroupListPage() {
		click(By.linkText("group page"));
	}

	private void submitGroupCreation() {
		click(By.name("submit"));
	}
	
	private void fillGroupForm(GroupObject groupObject) {
		type(By.name("group_name"), groupObject.name);
		type(By.name("group_header"), groupObject.header);
		type(By.name("group_footer"), groupObject.footer);
	}
	
	private void initGroupCreation() {
		click(By.name("new"));
	}

	public void deleteGroup(GroupObject someGroup) {
		manager.getNavigationHelper().goToGroupListPage();
		//checkGroup(someGroup);
		click(By.name("delete"));
		returnToGroupListPage();
		buildGroupCashe();
	}
	
	private void checkGroup(int i) {
		click(By.name("selected[]"));
	}
	
	public void modifyGroup(int i, GroupObject groupObject) {
		manager.getNavigationHelper().goToGroupListPage();
		initGroupModification(i);
		fillGroupForm(groupObject);
		submitGroupModification();
		returnToGroupListPage();
		buildGroupCashe();
	}
	
	private void submitGroupModification() {
		click(By.name("update"));
	}

	private void initGroupModification(int i) {
		checkGroup(i);
		click(By.name("edit"));
		
	}
}
